package com.dji.sample.manage.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.dji.sample.common.model.CustomClaim;
import com.dji.sample.common.model.PaginationData;
import com.dji.sample.common.model.ResponseResult;
import com.dji.sample.manage.model.dto.FireCheckRecordAddDTO;
import com.dji.sample.manage.model.dto.FireCheckRecordQuery;
import com.dji.sample.manage.model.entity.FireCheckRecordEntity;
import com.dji.sample.manage.service.FireCheckRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;

import static com.dji.sample.component.AuthInterceptor.TOKEN_CLAIM;

/**
 * @author yjt
 * @date 2022-11-11
 * @description:
 */
@RestController
@RequestMapping("fire")
public class FireCheckRecordController {

    @Autowired
    FireCheckRecordService fireCheckRecordService;

    @Resource
    RedisTemplate<String, String> redisTemplate;

    //开启火情检测
    @PostMapping("check/enable")
    public ResponseResult<?> enableCheck(@RequestParam String deviceSn){
        fireCheckRecordService.enableFireCheck(deviceSn);
        return ResponseResult.success();
    }

    @PostMapping("record/save")
    public ResponseResult<?> add(@RequestBody FireCheckRecordAddDTO fireCheckRecordAddDTO, HttpServletRequest request) {
        CustomClaim customClaim = (CustomClaim)request.getAttribute(TOKEN_CLAIM);
        fireCheckRecordAddDTO.setOrgId(customClaim.getOrgId());
        fireCheckRecordAddDTO.setOrgCode(customClaim.getOrgCode());
        fireCheckRecordService.addFireCheckRecord(fireCheckRecordAddDTO);
        return ResponseResult.success("添加成功");
    }

    @PostMapping("record/page")
    public ResponseResult<PaginationData<FireCheckRecordEntity>> page(@RequestBody FireCheckRecordQuery query) {
        return ResponseResult.success(fireCheckRecordService.page(query));
    }

    @PostMapping("check/status")
    public ResponseResult<?> getStatus(@RequestParam String deviceSn){
        if(Boolean.TRUE.equals(redisTemplate.hasKey(getFireCheckKey(deviceSn)))){
            return ResponseResult.success();
        }
        return ResponseResult.error();
    }


    public static String getFireCheckKey (String deviceSn){
        return String.format("fire:device:%s",deviceSn);
    }
}
